package cn.minhx.lab.design_patterns.adapter.f2.fields;

import com.alibaba.fastjson2.JSON;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class MessageAdapter {

    public static CommonMessage filter(String strJson, Map<String, String> link) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        return filter(JSON.parseObject(strJson, Map.class), link);
    }

    public static CommonMessage filter(Map<Object, Object> obj, Map<String, String> link) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        CommonMessage commonMessage = new CommonMessage();
        Class<CommonMessage> clazz = CommonMessage.class;
        for (String key : link.keySet()) {
            Object val = obj.get(link.get(key));

            // 方法名
            String methodName = "set" + key.substring(0, 1).toUpperCase() + key.substring(1);
            // 目标方法
            Method targetMethod = clazz.getMethod(methodName, String.class);
            // 调用方法，设置值
            targetMethod.invoke(commonMessage, val.toString());
        }
        return commonMessage;
    }

}
